package com.larry.design.structural.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author larry
 * @Title: design-frame
 * @Package com.larry.design.structural.proxy.cglib
 * @Description: TODO
 * @date 9/1/212:38 PM
 */
public class CglibProxy {

    /**
     * 为任意对象创建代理
     * @param t
     * @param <T>
     * @return
     */
    public static<T> T createProxy(T t){
        //创建一个增强器
        Enhancer enhancer = new Enhancer();

        //增强器为要增强的类动态创建一个子类
        enhancer.setSuperclass(t.getClass());

        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                Object invoke = methodProxy.invokeSuper(o, objects);

                return invoke;

            }
        });

        Object o = enhancer.create();
        return (T) o;
    }

}
